<template>
  <section>
    <iframe src="" frameborder="0" width="0" height="0" id="paiziID"></iframe>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <span>状态：</span>
          <el-radio-group v-model="selectItem.type" @change="currentChange">
            <el-radio-button v-for="(item, index) in typeMaps" :label="item.value" name="status" :key="index">{{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <div style="display: inline-block;float: right">
          <el-form :inline="true">
            <el-select v-model="selectItem.query" placeholder="请选择" @change="currentSelChange">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-form-item>
              <el-input :placeholder="selectItem.query" v-model="selectItem.keywords" v-if="selectItem.query != 'area_name'" @keyup.enter.native="doSearch"></el-input>
              <select v-model="selectItem.keywords" style="width: 170px;height: 35px;border-radius: 5px;font-size: 18px;" @change="doSearch" v-else>
                <option :value="item" v-for="(item, index) in areaName">{{ item }}</option>
              </select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" v-on:click="doSearch">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="background: #13ce66" v-on:click="_reload">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="fieldsData" border style="width: 100%" v-loading="loading" :row-class-name="tableRowClassName" @sort-change="timeSort" element-loading-text="玩命请求中。。。">
      <el-table-column prop="id" label="id" width="70">
      </el-table-column>
      <el-table-column prop="sn" label="期数" width="80">
      </el-table-column>
      <!--<el-table-column prop="farm_id" label="农场" width="65" :formatter="farmName">-->
      <!--</el-table-column>-->
      <el-table-column prop="area_name" label="区名" width="80">
      </el-table-column>
      <el-table-column prop="name" label="地名" width="65">
      </el-table-column>
      <el-table-column label="种植信息" width="195">
        <template slot-scope="scope">
          <div v-if="scope.row.plant_name">
            <div class="field_list_left">
              <img :src="scope.row.list_pic" alt="">
            </div>
            <div class="field_list_right">
              <p>{{ scope.row.plant_maturity }}</p>
              <p>{{ scope.row.plant_name }}</p>
            </div>
          </div>
          <span v-else>暂未种植</span>
        </template>
      </el-table-column>
      <el-table-column label="浇水cd(时)">
        <template slot-scope="scope">
          <cdInput :val="scope.row.water_interval" :field_name="cd_name[0]" :sn="scope.row.sn"></cdInput>
        </template>
      </el-table-column>
      <el-table-column label="施肥cd(时)">
        <template slot-scope="scope">
          <cdInput :val="scope.row.fert_interval" :field_name="cd_name[1]" :sn="scope.row.sn"></cdInput>
        </template>
      </el-table-column>
      <el-table-column label="除草cd(时)">
        <template slot-scope="scope">
          <cdInput :val="scope.row.weed_interval" :field_name="cd_name[2]" :sn="scope.row.sn"></cdInput>
        </template>
      </el-table-column>
      <el-table-column label="除虫cd(时)">
        <template slot-scope="scope">
          <cdInput :val="scope.row.bug_interval" :field_name="cd_name[3]" :sn="scope.row.sn"></cdInput>
        </template>
      </el-table-column>
      <el-table-column prop="production" label="产量(斤)" width="65" :formatter="changeProduction">
      </el-table-column>
      <el-table-column prop="price" label="售价(元)" width="65" :formatter="changePrice">
      </el-table-column>
       <el-table-column prop="orgin_price" label="标价(元)" width="65" :formatter="changeOrginPrice">
      </el-table-column>
      <el-table-column prop="sold" label="已售" width="65">
      </el-table-column>
      <el-table-column prop="inventory" label="份数" width="65">
      </el-table-column>
      <el-table-column prop="plant_time" label="种植时间" width="115" :sortable="'custom'">
      </el-table-column>
      <el-table-column prop="collect_time" label="预熟时间" width="115" :formatter="collectTime" :sortable="'custom'">
      </el-table-column>
      <el-table-column prop="sn_create_time" label="创建时间" width="160" :formatter="createTime" :sortable="'custom'">
      </el-table-column>
      <el-table-column label="操作" width="170" fixed="right">
        <template slot-scope="scope">
          <div style="margin-left: 5px;">
            <el-button size="small" @click="editNewSn(scope.row.id, scope.row.sn)" v-if="editButton && scope.row.sn != 0 && parseInt(scope.row.collect_time) > sn_now">编辑</el-button>
            <el-button type="danger" size="small" @click="addNewSn(scope.row.id)" v-if="addButton && parseInt(scope.row.collect_time) <= sn_now" >新增</el-button>
            <el-button type="default" size="small" @click="builPaizi(scope.row)" >打印牌子</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--新增新一期菜品-->
    <el-dialog title="新增菜品" v-model="addSnShow" :close-on-click-modal="false">
      <el-form :model="addSnForm" label-width="80px" ref="addForm">

        <el-form-item label="蔬菜名" prop="plant_name">
          <template slot-scope="scope">
            <select v-model="addSnForm.plant_name" style="width: 100px;height: 30px;" @change="">
              <option value="">请选择</option>
              <option :value="item" v-for="(item, index) in plants">{{ item }}</option>
            </select>
          </template>
        </el-form-item>

        <el-form-item label="成熟期" prop="plant_maturity">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="addSnForm.plant_maturity" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：25-30 或者 25</span>
          </template>
        </el-form-item>

        <el-form-item label="种植时间">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-date-picker v-model="addSnForm.plant_time" type="date" placeholder="选择日期" @change="changePlantDate(1)"></el-date-picker>
            </div>
            <span style="margin-left: -95px;">例如：2017-07-31</span>
          </template>
        </el-form-item>

        <el-form-item label="预熟时间">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-date-picker v-model="addSnForm.plan_date" type="date" placeholder="选择日期" :picker-options="pickerPtions"></el-date-picker>
            </div>
            <span style="margin-left: -95px;">例如：2017-07-21</span>
          </template>
        </el-form-item>

        <el-form-item label="预估产量" prop="production">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="addSnForm.production" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：300斤-输入数字</span>
          </template>
        </el-form-item>

        <el-form-item label="库存" prop="inventory">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="addSnForm.inventory" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：30(份)-输入数字</span>
          </template>
        </el-form-item>

        <el-form-item label="售价" prop="price">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="addSnForm.price" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：59(元)-输入数字</span>
          </template>
        </el-form-item>

        <el-form-item label="标价" prop="orgin_price">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="addSnForm.orgin_price" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：59(元)-输入数字</span>
          </template>
        </el-form-item>
        
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addSnShow = false">取消</el-button>
        <el-button type="primary" @click.native="addNewSnField" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--编辑当前期菜品信息-->
    <el-dialog title="编辑当前种植菜品信息" v-model="editSnShow" :close-on-click-modal="false">
      <el-form :model="editSnForm" label-width="80px" ref="editForm">

        <el-form-item label="蔬菜名" prop="plant_name">
          <template slot-scope="scope">
            <select v-model="editSnForm.plant_name" style="width: 100px;height: 30px;" @change="changeSelectPlant(2)">
              <option value="">请选择</option>
              <option :value="item" v-for="(item, index) in plants">{{ item }}</option>
            </select>
          </template>
        </el-form-item>

        <el-form-item label="成熟期" prop="plant_maturity">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="editSnForm.plant_maturity" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：25-30 或者 25</span>
          </template>
        </el-form-item>

        <el-form-item label="种植时间">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-date-picker v-model="editSnForm.plant_time" type="date" placeholder="选择日期" @change="changePlantDate(2)"></el-date-picker>
            </div>
            <span style="margin-left: -95px;">例如：2017-07-31</span>
          </template>
        </el-form-item>

        <el-form-item label="预熟时间">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-date-picker v-model="editSnForm.plan_date" type="date" placeholder="选择日期" :picker-options="pickerPtions"></el-date-picker>
            </div>
            <span style="margin-left: -95px;">例如：2017-07-21</span>
          </template>
        </el-form-item>

        <el-form-item label="预估产量" prop="production">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="editSnForm.production" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：300斤-输入数字</span>
          </template>
        </el-form-item>

        <el-form-item label="库存" prop="inventory">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="editSnForm.inventory" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：30(份)-输入数字</span>
          </template>
        </el-form-item>

        <el-form-item label="售价" prop="price">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="editSnForm.price" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：59(元)-输入数字</span>
          </template>
        </el-form-item>

        <el-form-item label="标价" prop="price">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="editSnForm.orgin_price" auto-complete="on"></el-input>
            </div>
            <span style="margin-left: 10px;">例如：59(元)-输入数字</span>
          </template>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editSnShow = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--分页-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        @current-change="currentPageChange"
        :page-size="30"
        layout="prev, pager, next, jumper"
        :total="total" style="float:right;" :current-page="parseInt(selectItem.page)">
      </el-pagination>
      <span style="float: right;margin-top: 6px;margin-right: 5px">共 {{total}} 条数据</span>
    </el-col>

  </section>
</template>

<script>
  import util from '../../util'
  import NProgress from 'nprogress'
  import cdInput from '../common/cdInput'
  import { isUrlHasPurview } from '../../vuex/getters'
  import { apiTree } from '../../apiTree'

  export default {
    name: 'field',
    // 局部注册组件
    components: {
      cdInput
    },
    data() {
      return {
        loading: false,
        pickerPtions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        options: [
          {value: 'area_name', label: '区域名'},
          {value: 'map_id', label: '土地id'},
          {value: 'plant_name', label: '菜品'}
        ],
        typeMaps: [
          {value: -1, label: '全部'},
          {value: 1, label: '待种植'},
          {value: 2, label: '种植中'}
        ],
        selectItem: {
          page: this.$route.query.page !== undefined ? this.$route.query.page : 1,
          query: this.$route.query.query !== undefined ? this.$route.query.query : '',
          keywords: this.$route.query.keywords !== undefined ? this.$route.query.keywords : '',
          type: this.$route.query.type !== undefined ? this.$route.query.type : -1,
          sort: this.$route.query.sort !== undefined ? this.$route.query.sort : 0,
          sortType: this.$route.query.sortType !== undefined ? this.$route.query.sortType : ''
        },
        fieldsData: [],
        total: 0,
        sn_now: Math.ceil(parseInt(new Date().getTime()) / 1000),
        cd_name: ['water_interval', 'fert_interval', 'weed_interval', 'bug_interval', 'inventory'],
        addSnShow: false,
        editSnShow: false,
        addLoading: false,
        plants: [],
        areaName: [],
        // 新增菜品
        addSnForm: {
          id: 0,
          plant_name: '',
          plant_maturity: '',
          plan_date: '',
          plant_time: '',
          inventory: 0,
          price: 0,
          orgin_price: 0,
          production: 0
        },
        // 编辑框
        editSnForm: {
          id: 0,
          sn: 0,
          plant_name: '',
          plant_maturity: '',
          plan_date: '',
          plant_time: '',
          inventory: 0,
          price: 0,
          orgin_price: 0,
          production: 0
        }
      }
    },
    computed: {
      // 编辑菜品权限
      editButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'field/editField'))
      },
      // 新增管理员权限
      addButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'field/addField'))
      }
    },
    methods: {
      // 打印牌子
      builPaizi(row) {
        document.getElementById('paiziID').src = '/index.php?c=other&a=buildPaizi&params=' + encodeURIComponent(JSON.stringify({
          farm_id: row.farm_id,
          map_id: row.id,
          title: row.area_name + row.name,
          plant_name: row.plant_name,
          plant_time: util.formatDate.format(new Date(row.plant_time), 'yyyy年MM月dd日'),
          collect_time: util.formatDate.format(new Date(row.collect_time * 1000), 'yyyy年MM月dd日')
        }));
      },
      // 转变产量为斤
      changeProduction(row) {
        return parseInt(row.production) / 500
      },
      // 转变单价为元
      changePrice(row) {
        return parseInt(row.price) / 100
      },
      changeOrginPrice(row) {
      	return parseInt(row.orgin_price) / 100
      },
      // 农场名称
      farmName(row, column) {
        return row.farm_id === '1' ? '枫泾' : '其他农场'
      },
      // 预熟时间
      collectTime(row, column) {
        return row.collect_time === 0 ? 0 : util.formatDate.format(new Date(row.collect_time * 1000), 'yyyy-MM-dd')
      },
      // 创建时间
      createTime(row) {
        if (!row.sn_create_time) {
          return 0
        }
        return row.sn_create_time.substring(2)
      },
      // 修改时间
      formatTime(_time) {
        return util.formatDate.format(new Date(_time * 1000), 'yyyy-MM-dd hh:mm:ss').substring(2)
      },
      // 选择页码
      currentPageChange(val) {
        this.selectItem.page = val
        this.$router.push({path: this.$route.path, query: this.selectItem})
      },
      // 时间排序
      timeSort(column) {
        let sort = 1; // 降序
        let sortType = '';
        if (column.prop === 'plant_time') {
          sortType = 'plant_time';
        }
        if (column.prop === 'collect_time') {
          sortType = 'collect_time';
        }
        if (column.prop === 'sn_create_time') {
          sortType = 'sn_create_time';
        }
        if (column.order === 'ascending') {
          sort = 2; // 升序
        }
        if (this.selectItem.type != 2) {
          return
        }
        this.selectItem.sort = sort;
        this.selectItem.sortType = sortType;
        this.selectItem.page = 1;
        this.$router.push({path: this.$route.path, query: this.selectItem});
      },
      // 选项卡选择
      currentChange() {
        this.$router.push({path: this.$route.path, query: this.selectItem})
      },
      // 下拉框变化
      currentSelChange() {
        if (this.selectItem.query === 'area_name') {
          this.getAreaName()
        } else {
          this.selectItem.keywords = ''
        }
      },
      // 搜索
      doSearch() {
        if (this.selectItem.query === 'area_name' && util.isEmpty(this.selectItem.keywords)) {
          return;
        }
        if (this.selectItem.query) {
          this.$router.push({path: this.$route.path, query: this.selectItem})
        }
      },
      // td ClassName
      tableRowClassName(row) {
        let t = parseInt(row.collect_time)
        if (t <= this.sn_now || !util.isEmpty(t)) {
          return 'expire-row'
        } else {
          return ''
        }
      },
      // 翻种新一期土地
      addNewSn(id) {
        this.addSnShow = true;
        this.getPlantName();
        this.addSnForm.id = id;
      },
      // 改变选择种子，一些数据变化
      changeSelectPlant(_type) {
        let para = {};
        if (_type === 1) {
          para = {name: this.addSnForm.plant_name};
        } else {
          para = {name: this.editSnForm.plant_name};
        }
        apiTree('field/index', 'field/getSinglePlantInfo', para).then((res) => {
          if (res.s === 1) {
            if (_type === 1) {
              this.addSnForm.plant_maturity = res.d.maturity;
              this.addSnForm.inventory = res.d.inventory;
              this.addSnForm.price = parseInt(res.d.price) / 100;
              this.addSnForm.orgin_price = parseInt(res.d.orgin_price) / 100;
              this.addSnForm.production = parseInt(res.d.production) / 500;
            } else if (_type === 2) {
              this.editSnForm.plant_maturity = res.d.maturity;
              this.editSnForm.inventory = res.d.inventory;
              this.editSnForm.price = parseInt(res.d.price) / 100;
              this.editSnForm.orgin_price = parseInt(res.d.orgin_price) / 100;
              this.editSnForm.production = parseInt(res.d.production) / 500;
              this.editSnForm.plant_time = '';
              this.editSnForm.plan_date = '';
            }
          }
        });
      },
      // 选择种植日期
      changePlantDate(_type) {
        if (_type === 1) {
          if (!util.isEmpty(this.addSnForm.plant_maturity) && util.isInt(this.addSnForm.plant_maturity)) {
            let _dateTime = parseInt(new Date(this.addSnForm.plant_time).getTime()) + parseInt(this.addSnForm.plant_maturity) * 24 * 3600 * 1000;
            this.addSnForm.plan_date = util.formatDate.format(new Date(_dateTime), 'yyyy-MM-dd');
          }
        }
        if (_type === 2) {
          if (!util.isEmpty(this.editSnForm.plant_maturity) && util.isInt(this.editSnForm.plant_maturity)) {
            let _dateTime = parseInt(new Date(this.editSnForm.plant_time).getTime()) + parseInt(this.editSnForm.plant_maturity) * 24 * 3600 * 1000;
            this.editSnForm.plan_date = util.formatDate.format(new Date(_dateTime), 'yyyy-MM-dd');
          }
        }
      },
      // 提交翻种的新一期土地信息
      addNewSnField() {
        this.$confirm('确认提交吗？', '提示', {}).then(() => {
          NProgress.start();
          if (!util.isInt(this.addSnForm.production, true)) {
            this.$message.error('请输入数字')
            return
          }
          if (this.addSnForm.plan_date.length <= 0) {
            this.$message.error('请选择日期')
            return
          }
          if (this.addSnForm.plant_time.length <= 0) {
            this.$message.error('请选择种植日期')
            return
          }
          apiTree('field/addField', 'field/setField', this.addSnForm, 'POST').then((res) => {
            if (res.s === 1) {
              NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addSnShow = false;
              this.getFields()
            } else if (res.s < 1) {
              this.$message.error(res.err_str)
              return
            }
          })
        })
      },
      // 编辑最新一期菜品
      editNewSn(_id, _sn) {
        this.editSnShow = true
        this.getPlantName()
        let param = {'sn': _sn}
        apiTree('field/index', 'field/plantParam', param).then((res) => {
          if (res.s === 1) {
            res = res.d
            this.editSnForm = {
              'id': _id,
              'sn': res.sn,
              'plant_name': res.plant_name,
              'plant_maturity': res.plant_maturity.substr(0, res.plant_maturity.length - 1),
              'plan_date': util.formatDate.format(new Date(res.collect_time * 1000), 'yyyy-MM-dd'),
              'plant_time': res.plant_time,
              'inventory': res.inventory,
              'price': parseInt(res.price) / 100,
              'orgin_price': parseInt(res.orgin_price) / 100,
              'production': parseInt(res.production) / 500
            }
          }
        })
      },
      // 编辑提交
      editSubmit() {
        this.$confirm('确认提交吗？', '提示', {}).then(() => {
          NProgress.start()
          if (!util.isInt(this.editSnForm.production, true)) {
            this.$message.error('请输入数字')
            return
          }
          if (this.editSnForm.plan_date.length <= 0) {
            this.$message.error('请选择成熟日期')
            return
          }
          if (this.editSnForm.plant_time.length <= 0) {
            this.$message.error('请选择种植日期')
            return
          }
          apiTree('field/editField', 'field/setField', this.editSnForm, 'POST').then((res) => {
            if (res.s === 1) {
              NProgress.done();
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.$refs['editForm'].resetFields()
              this.editSnShow = false
              this.getFields()
            } else if (res.s < 1) {
              this.$message.error(res.err_str)
              return
            }
          })
        })
      },
      // 刷新页面
      _reload() {
        this.getFields()
      },
      // 获得植物名
      getPlantName() {
        this.plants = []
        apiTree('field/index', 'field/getAllPlantName', {}).then((res) => {
          if (res.s === 1) {
            res.d.data.forEach((item) => {
              this.plants.push(item.name);
            })
          }
        })
      },
      // 获得区域名
      getAreaName() {
        this.areaName = []
        apiTree('field/index', 'field/getAreaName', {}).then((res) => {
          if (res.s === 1) {
            res.d.data.forEach((item) => {
              this.areaName.push(item.area_name)
            })
          }
        })
      },
      // 获得土地列表
      getFields() {
        let param = this.$route.query
        if (util.isEmptyObject(param)) {
          this.selectOptions = {
            page: 1,
            query: '',
            keywords: '',
            type: -1,
            sort: 0,
            sortType: ''
          }
        }
        this.loading = true
        NProgress.start()
        apiTree('field/index', 'field/index', param).then((res) => {
          if (res.s === 1) {
            this.total = res.d.total_num
            this.fieldsData = res.d.data
            this.loading = false
            NProgress.done()
          }
        })
      }
    },
    created() {
      this.getFields();
      this.getAreaName();
    },
    watch: {
      $route: 'getFields'
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .field_list_left
    display inline-block
    vertical-align middle
    margin-top 5px
    & img
      width 90px
      height 50px
  .field_list_right
    display inline-block
    vertical-align middle
    margin-left 5px
  .el-table .expire-row
    background #e2f0e4
  .el-form-item
    margin-bottom 10px
</style>
